package backingBean;

import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import abstractFactory.Factory;
import model.Card;
import dao.Card.CardDAO;

public class BeanCard {
	private Card card = new Card();
	//private List<Card> cards;

	public BeanCard(){}

	public Card getCard() {
		return card;
	}

	public void setCard(Card card) {
		this.card = card;
	}

	public void register(){
		CardDAO cardDao = Factory.getInstance("JPA").createCardDAO();
		if(cardDao.save(card)){
			FacesMessage msg = new FacesMessage("Cadastrado com Sucesso.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
			card = new Card();
		}	
		else{
			FacesMessage msg = new FacesMessage("Tente outra vez.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
		}	
	}

	public List<Card> getCards(){
		CardDAO cardDao = Factory.getInstance("JPA").createCardDAO();
		return cardDao.getAllCards();
	}
	
	public SelectItem[] getItemsCards(){
		SelectItem esule[] = new SelectItem[getCards().size()];
		for(int i=0; i<getCards().size();i++ ){
			esule[i] = new SelectItem(getCards().get(i),getCards().get(i).getFlag());
		}
		return esule;
	}

	public Card editCard(){
		return card;
	}

	public void delete(){
		CardDAO cardDao = Factory.getInstance("JPA").createCardDAO();
		card.setActive(0);
		cardDao.update(card);
		card = new Card();
	}
}